package io2.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;

public class NioServer2 {
    static final byte[] RS = "HTTP/1.1 200 OK\r\nContent-length:13\r\n\r\nHello, World!\r\n".getBytes();
    static LinkedList<SocketChannel> channels = new LinkedList<>();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        System.out.println("服务启动，监听8080端口");
        while(true) {
            SocketChannel accept = serverSocketChannel.accept();
            if(accept != null) {
                accept.configureBlocking(false);
                System.out.println("新建连接：" + accept.getRemoteAddress());
                channels.add(accept);
            }
            Iterator<SocketChannel> iterator = channels.iterator();
            while(iterator.hasNext()) {
                SocketChannel socketChannel = iterator.next();
                if(socketChannel != null && socketChannel.isConnected()) {
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    // 如果没有数据，则继续下一个
                    if (socketChannel.read(buffer) <= 0)
                        continue;
                    // 有数据就打印出来
                    buffer.flip();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    System.out.println("收到数据：" + new String(bytes));
                    buffer.clear();
                    System.out.println("数据接收完毕， 来源于：" + socketChannel.getRemoteAddress());
                    // 返回结果
                    socketChannel.write(ByteBuffer.wrap(RS));
                    System.out.println("数据发送完毕");
                    // 关闭通道
                    socketChannel.close();
                    // 删除通道
                    iterator.remove();
                }
            }
        }
    }
}
